import { httpClient } from '../base/request'
import { authAPIConfig } from './const/api'
import { ApiResponse } from '../type/request'
// import { firebaseTracker } from "@/tracking/trackers/FirebaseTracker";
// import { TRACKING_EVENTS } from "@/tracking/constants/eventTypes";

export const AuthService = {
  // 如果某个特定接口需要特殊的错误处理，那么才需要在该方法中使用 try-catch。否则，应该依赖统一的错误处理机制。

  async getGoogleAuthUrl(redirectRouteName: string = 'home') {
    const callbackPath = `auth/callback?routeName=${redirectRouteName}`

    try {
      const { data } = await httpClient.request<ApiResponse<string>>({
        url: authAPIConfig.getGoogleAuthUrl,
        params: {
          state: callbackPath,
        },
      })
      return data
    } catch (error) {
      console.error('Failed to get Google auth URL:', error)
      throw error
    }
  },

  // 解析URL中的认证信息
  parseAuthResponse(urlPath: string): Auth.LoginResponse {
    try {
      // 从 URL 中提取认证数据部分
      const authDataEncoded = urlPath.split('/auth/callback?')[1]
      console.log({ authDataEncoded })
      if (!authDataEncoded) {
        throw new Error('Invalid auth callback URL')
      }

      // 解析 URL 参数
      const urlParams = new URLSearchParams(authDataEncoded)
      const fullRouteNameParam = urlParams.get('routeName') || ''

      // 使用 '/' 分割获取路由名称和认证数据
      const [routeName, ...authDataParts] = fullRouteNameParam.split('/')

      // 重新组合认证数据部分（因为数据中可能包含 '/'）
      const authDataStr = authDataParts.join('/')

      if (!authDataStr) {
        throw new Error('No auth data found')
      }

      // 解析认证数据
      const authData = JSON.parse(decodeURIComponent(authDataStr))

      return {
        tokens: {
          accessToken: authData.accessToken,
          refreshToken: authData.refreshToken,
          expiresIn: authData.expiresIn,
          refreshExpiresIn: authData.refreshExpiresIn,
          userId: authData.userId,
          userEmail: authData.email,
          userAvatar: authData.pictureUrl,
        },
        routeName,
      }
    } catch (error) {
      console.error('Failed to parse auth data:', error)
      // 返回一个默认响应，或者根据需求处理错误
      return {
        tokens: {
          accessToken: '',
          refreshToken: '',
          expiresIn: 0,
          refreshExpiresIn: 0,
          userId: '',
          userEmail: '',
          userAvatar: '',
        },
        routeName: '',
      }
    }
  },

  // 例如使用refresh Token刷新access token
  async getUserToken(params: Auth.LoginParams) {
    const { data } = await httpClient.request<Auth.TokenInfoRes>({
      url: authAPIConfig.getUserToken,
      params,
    })
    return data
  },
}
